package com.wyix;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author wangdx
 * @since 2025/8/5
 */
public class HttpPostDemo {
    public static void main(String[] args) throws Exception {
        URL url = new URL("https://jsonplaceholder.typicode.com/posts");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        // 设置POST请求
        connection.setRequestMethod("POST");
        connection.setDoOutput(true); // 允许输出（发送请求体）

        // 设置请求头（JSON类型）
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.setRequestProperty("Accept", "application/json");

        // 构建请求体（JSON数据）
        String jsonInputString = "{\"name\": \"John\", \"email\": \"john@example.com\"}";

        // 发送请求体
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = jsonInputString.getBytes("UTF-8");
            os.write(input, 0, input.length);
        }

        // 获取响应
        int responseCode = connection.getResponseCode();
        System.out.println("POST响应状态码: " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_CREATED) {
            // 读取响应体
            try (BufferedReader in = new BufferedReader(
                    new InputStreamReader(connection.getInputStream()))) {
                String line;
                StringBuilder response = new StringBuilder();
                while ((line = in.readLine()) != null) {
                    response.append(line);
                }
                System.out.println("响应内容: " + response.toString());
            }
        } else {
            System.out.println("请求失败: " + connection.getResponseMessage());
        }

        connection.disconnect();
    }
}
